<script>
    function parseLRC(lrcText) {
        const lines = lrcText.split('\n');
        const lrcData = [];
        const timeRegex = /\[(\d{2}):(\d{2})\.(\d{2,3})\]/;

        lines.forEach(line => {
            const match = line.match(timeRegex);
            if (match) {
                const time = parseInt(match[1]) * 60 + parseInt(match[2]) + (parseInt(match[3]) / 1000);
                const text = line.replace(timeRegex, '').trim();
                lrcData.push({time, text});
            }
        });

        return lrcData;
    }

    async function playMusic(audioUrl, title, artist, lrcUrl, musicId) {
        document.getElementById('songTitle').querySelector('span').textContent = `歌曲名：${title}`;
        document.getElementById('songArtist').querySelector('span').textContent = `歌手：${artist}`;
        var player = document.getElementById('audioPlayer');
        // 显示播放器
        player.style.display = 'block';

        player.src = audioUrl;
        player.play();

        try {
            // 从URL获取歌词文本
            const response = await fetch(lrcUrl);
            const lrcText = await response.text();

            // 解析LRC文本
            const lrcData = parseLRC(lrcText);

            // 当音频时间更新时，更新显示的歌词
            player.ontimeupdate = () => {
                const currentTime = player.currentTime;
                updateLyric(currentTime, lrcData);
            };

            await fetch(`/music/${musicId}/music_click/`);
        } catch (error) {
            console.error("Error fetching or parsing LRC:", error);
        }
    }

    function updateLyric(currentTime, lrcData) {
        const currentLine = lrcData.find((line, index) => (
            index === lrcData.length - 1 || (currentTime >= line.time && currentTime < lrcData[index + 1]?.time)
        ));
        if (currentLine) {
            document.getElementById('currentLyric').textContent = currentLine.text;
        }
    }

    function toggleCollection(icon) {
        const musicId = icon.getAttribute('data-music-id');
        console.log(musicId)
        const isCurrentlyCollected = icon.classList.contains('fas'); // 检查图标是否已经是实心的

        const url = `/music/${musicId}/collection/`;
        const method = isCurrentlyCollected ? 'DELETE' : 'POST';

        fetch(url, {
            method: method,
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCookie('csrftoken')
            }
        })
            .then(response => {
                if (response.ok) {
                    // 切换图标样式
                    icon.classList.toggle('fas');
                    icon.classList.toggle('far');
                    // 根据收藏状态显示不同颜色
                    if (isCurrentlyCollected) {
                        icon.style.color = 'grey'; // 已取消收藏，变成空心，灰色
                    } else {
                        icon.style.color = 'red'; // 已收藏，变成实心，红色
                    }
                } else {
                    console.error('Failed to toggle collection status');
                }
            })
            .catch(error => console.error('Error toggling collection status:', error));
    }

    function getCookie(name) {
        const value = `; ${document.cookie}`;
        const parts = value.split(`; ${name}=`);
        if (parts.length === 2) return parts.pop().split(';').shift();
    }
</script>
<style>
    #audioPlayer {
        display: none; /* 初始隐藏播放器 */
        position: fixed;
        bottom: 0;
        left: 0;
        width: calc(100% - 230px);
        margin-left: 240px;
        z-index: 100;
    }

    .audio-info {
        display: flex;
        align-items: center;
        gap: 10px; /* 调整间距 */
    }

    #audioDetails {
        margin-left: 20px; /* 根据需要调整 */
    }

    #lyricsContainer {
        margin-top: 20px;
    }

    #currentLyric {
        color: red;
        font-size: 18px; /* 设置字体大小 */
        font-family: Arial, sans-serif; /* 设置字体类型 */
    }
</style>
{% extends 'base.html' %}

{% block content %}
    <div class="audio-info">
        <audio id="audioPlayer" controls></audio>
        <div id="audioDetails">
            <p id="songTitle"><span></span></p>
            <p id="songArtist"><span></span></p>
            <div id="lyricsContainer">
                <p id="currentLyric"></p>
            </div>
        </div>
    </div>
    <div class="container mt-4">
        <ul class="list-group">
            {% for music in genre_list %}
                <li class="list-group-item d-flex align-items-center">
                    <img src="{{ music.pic_url }}" alt="{{ music.name }}" class="me-3"
                         style="width: 60px; height: auto; border-radius: 0.25rem;">
                    <div class="flex-grow-1">
                        <h5 class="mb-1">{{ music.name }}</h5>
                        <p class="mb-0">作者: {{ music.author }}</p>
                    </div>
                    <div>
                        <button onclick="playMusic('{{ music.audio_path }}', '{{ music.name }}', '{{ music.author }}', '{{ music.lrc }}', '{{ music.id }}')"
                                class="btn btn-primary me-2">播放
                        </button>
                        {% if music.is_collection %}
                            <i class="far fa-heart" style="color: red;" onclick="toggleCollection(this)"
                               data-music-id="{{ music.id }}"></i>
                        {% else %}
                            <i class="far fa-heart" style="color: grey;" onclick="toggleCollection(this)"
                               data-music-id="{{ music.id }}"></i>
                        {% endif %}
                    </div>
                </li>
            {% endfor %}
        </ul>
        <div class="page" id="newpage">
            <div class="layui-box layui-laypage layui-laypage-default" id="layui-laypage-0">
                {% if music_page.has_previous %}
                    <a href="?page=1&genre_id={{ genre_id }}&music_name={{ music_name }}" class="layui-laypage-last"
                       title="首页">首页</a>
                    <a href="?page={{ music_page.previous_page_number }}&genre_id={{ genre_id }}&music_name={{ music_name }}"
                       class="layui-laypage-last" title="上一页">上一页</a>
                {% endif %}
                {% if music_page.number > 4 %}
                    <span>...</span>
                {% endif %}

                {# 显示当前页码的前后各三页 #}
                {% for num in music_page.paginator.page_range %}
                    {% if num > music_page.number|add:'-4' and num < music_page.number|add:'4' %}
                        {% if music_page.number == num %}
                            <a href="?page={{ num }}&genre_id={{ genre_id }}&music_name={{ music_name }}"
                               class='on'>{{ num }}</a>
                        {% else %}
                            <a href="?page={{ num }}&genre_id={{ genre_id }}&music_name={{ music_name }}">{{ num }}</a>
                        {% endif %}
                    {% endif %}
                {% endfor %}

                {# 如果当前页码后面的页码数大于3，显示省略号 #}
                {% if music_page.paginator.num_pages > music_page.number|add:3 %}
                    <span>...</span>
                {% endif %}
                {% if music_page.has_next %}
                    <a href="?page={{ music_page.next_page_number }}&genre_id={{ genre_id }}&music_name={{ music_name }}"
                       class="layui-laypage-next">下一页</a>
                    <a href="?page={{ music_page.paginator.num_pages }}&genre_id={{ genre_id }}&music_name={{ music_name }}"
                       class="layui-laypage-last" title="末页">末页</a>
                {% endif %}
            </div>
        </div>
    </div>
{% endblock %}